import React, { createContext, useState, useEffect, useContext } from 'react';

const WebSocketContext = createContext(null);

export const WebSocketProvider = ({ children }) => {
    const [socket, setSocket] = useState(null);

    const connectWebSocket = (token) => {
        if (socket) return;
        const Language = localStorage.getItem('language') || 'en';
        const isHttps = -1 !== location.protocol.indexOf('https');
        const wsUrl = `${isHttps ? 'wss' : 'ws'}${WEBSOCKET_URL}`;
        const ws = new WebSocket(`${wsUrl}/message?token=${token}&Accept-Language=${Language}`);

        ws.addEventListener('open', () => {
            console.log('WebSocket connection established!');
        });
        ws.addEventListener('message', (event) => {
            try {
                // 处理 WebSocket 消息
            } catch (error) {
                console.error('Error parsing WebSocket message:', error);
            }
        });
        ws.addEventListener('close', () => {
            setSocket(null);
            console.log('WebSocket connection closed');
        });
        ws.addEventListener('error', (error) => {
            console.error('WebSocket error:', error);
        });
        setSocket(ws);
    };
    const disconnectWebSocket = () => {
        if (socket) {
            socket.close();
            setSocket(null);
            console.log('WebSocket connection closed manually');
        }
    };

    return (
        <WebSocketContext.Provider value={{ socket, connectWebSocket, disconnectWebSocket }}>
            {children}
        </WebSocketContext.Provider>
    );
};

export const useWebSocket = () => {
    return useContext(WebSocketContext);
};
